package gold.digger;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Created by fanzhenyu02 on 2020/3/1.
 */
public class LC204 {


    public int countPrimes(int n) {
        int count = 0;
        boolean[] isPrime = new boolean[n + 1];
        Arrays.fill(isPrime, true);

        for (int i = 2; i < n; i++) {
            if (isPrime[i]) {
                ++count;
                for (int j = 2; j * i < n; j++) {
                    isPrime[j * i] = false;
                }
            }
        }

        return count;
    }


    public List<Integer> primeList = new ArrayList<>();

    public int countPrimes_try_01(int n) {

        int count = 0;
        for (int i = 2; i < n; i++) {
            if (isPrime(i)) {
                primeList.add(i);
                ++count;
            }
        }

        return count;
    }

    public boolean isPrime(int num) {
        if (num <= 3) {
            return num > 1;
        }
        // 不在6的倍数两侧的一定不是质数
        if (num % 6 != 1 && num % 6 != 5) {
            return false;
        }

        for (int prime : primeList) {
            if (num % prime == 0) {
                return false;
            }
        }

        int sqrt = (int) Math.sqrt(num);
        for (int i = 5; i <= sqrt; i += 6) {
            if (num % i == 0 || num % (i + 2) == 0) {
                return false;
            }
        }
        return true;
    }

    public static void main(String[] args) {
        LC204 an = new LC204();
        System.out.println(an.countPrimes(49979));
    }
}
